package com.myr.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myr.dao.PermissionMapper;
import com.myr.dao.UserMapper;
import com.myr.entity.MyUser;
import com.myr.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author myr
 * @version 1.0
 * @date 2023/1/3 12:26
 */
@Service
public class Userservice implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据账户查询用户信息
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        MyUser myUser = userMapper.selectOne(queryWrapper);
        if (myUser != null) {
            //2.查询用户具有的权限
            List<Permission> permissions = permissionMapper.findByUserid(myUser.getUserid());
            //返回一个UserDetails对象--他是一个接口，返回他的实现类
            /**
             * String username,账户
             * String password，密码
             * Collection<? extends GrantedAuthority> authorities:该用户具有的权限
             */
            Collection<? extends GrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            User user = new User(username, myUser.getUserpwd(), authorities);
            return user;
        }
        return null;
    }
}
